package com.wechat.order.controller.SellerController;

import com.google.common.collect.Maps;
import com.wechat.order.dataobject.ProductCategory;
import com.wechat.order.enums.ResultEnum;
import com.wechat.order.exception.SellException;
import com.wechat.order.service.CategoryService.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 买家类目
 * Created by zzy on 2017/12/20.
 */
@Controller
@RequestMapping("/seller/category")
public class SellCategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page",defaultValue = "1") Integer page,
                             @RequestParam(value = "size",defaultValue = "10") Integer size,
                             Map<String,Object> model){
        PageRequest pageRequest=new PageRequest(page-1,size);
        Page<ProductCategory> categoryPage=categoryService.findAll(pageRequest);
        model.put("categoryList",categoryPage.getContent());
        model.put("currentPage",page);
        model.put("size",size);
        model.put("categoryPage",categoryPage);

        return new ModelAndView("/category/list",model);
    }
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId",required = false) Integer categoryId,
                              Map map){
        ProductCategory category=new ProductCategory();
        if(categoryId!=null){
            category=categoryService.findOne(categoryId);
        }
        map.put("category",category);
        return  new ModelAndView("/category/index",map);
    }
    @PostMapping("/save")
    private ModelAndView save(@ModelAttribute ProductCategory productCategory){
        categoryService.save(productCategory);
        Map model= Maps.newHashMap();
        try {
            categoryService.save(productCategory);
        }catch (SellException e){
            model.put("msg", e.getMessage());
            model.put("url","/sell/seller/category/list");
            return new ModelAndView("/common/error",model);
        }
        model.put("msg", ResultEnum.SUCCESS.getMessage());
        model.put("url","/sell/seller/category/list");

        return new ModelAndView("common/success",model);
    }
}
